package org.example.SolutionNew002;

public class LinkedList05 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
//        head.next = new ListNode(2);
        head.next = head;
        head.next.next.next = head.next;
        LinkedList05 l = new LinkedList05();
        System.out.println(l.detectCycle(head).val);
    }

    //还有一个方法同找是否有环一样，用set保存着来做

    public ListNode detectCycle(ListNode head) {
        //先找快慢指针相遇点，再继续奔跑找入口
        if(head==null||head.next==null) return null;
        ListNode slow = head;
        ListNode fast = head;
        do{
            fast=fast.next.next;
            slow=slow.next;
            if(slow==fast){
                fast=head;
                while(fast!=slow){
                    fast=fast.next;
                    slow=slow.next;
                }
                return fast;
            }
        }while(fast!=null&&fast.next!=null&&fast!=slow);
        return null;
    }
}
